import {Button, Col, Form, Icon, Input, message, Modal, Row, Select} from 'antd';
import React from "react";
import {withRouter} from "react-router-dom";
import {fetchTableAndColumnsApi, fetchTableListApi, updateColumns} from "../api/projectConfig";

const FormItem = Form.Item;
const Option = Select.Option;

let uuid = 0;


class RelationVerify extends React.Component {

    defaultSuper = {id: 0, name: "", comment: "-不关联-"};


    state = {
        tableOptions: [],
        tableColumns: []
    };

    componentDidMount() {
        const {projectId, relationData} = this.props;
        console.info("relationJson:"+relationData.relationJson);

        let ret = fetchTableListApi(projectId, 'vo');
        ret.then(res => {
            var _list = res.data.data ? res.data.data : [];
            this.setState({...this.state, tableOptions: [this.defaultSuper, ..._list]});

            if (relationData.relationJson !== 'no') {
                // 初始化赋值
                this.initDefaultData(JSON.parse(relationData.relationJson));
            }
        })
    }


    initDefaultData = async data => {
        const {tableOptions} = this.state;
        const {form} = this.props;

        form.resetFields();


        let relationTable = data.relationTable;

        let arr = tableOptions.filter(v => v.name === relationTable);

        if (arr.length > 0) {
            let obj = {};
            let arrElement = arr[0];

            obj.relationTable = JSON.stringify(arrElement)


            let res = await fetchTableAndColumnsApi(arrElement.id);


            this.setState({...this.state, tableColumns: res.data.data.columns});

            obj.relationColumn = data.relationColumn;


            let keys = form.getFieldValue('keys');
            for (let i = 0; i < data.relationArr.length; i++) {
                uuid++;

                keys = keys.concat(uuid);

                obj[`relationValue-${i + 1}`] = data.relationArr[i].relationValue;
                obj[`alias-${i + 1}`] = data.relationArr[i].alias;

            }

            form.setFieldsValue({keys:keys})

            form.setFieldsValue({...obj})

        }

    }


    remove = (k) => {
        const {form} = this.props;
        const keys = form.getFieldValue('keys');
        if (keys.length === 1) {
            return;
        }

        form.setFieldsValue({
            keys: keys.filter(key => key !== k),
        });
    }

    add = () => {

        if (this.state.tableColumns.length === 0) {
            message.warn("请先选择关联表！");
            return;
        }

        uuid++;
        const {form} = this.props;
        const keys = form.getFieldValue('keys');
        const nextKeys = keys.concat(uuid);
        form.setFieldsValue({
            keys: nextKeys,
        });
    }


    onChange = (value, selectedOptions) => {
        console.log(value, selectedOptions);
    }


    handleOk = () => {

        const {relationData} = this.props;

        this.props.form.validateFields((err, values) => {
            if (!err) {

                // 数据进行处理

                console.log(values);
                console.log(values.keys);

                let tableId = JSON.parse(values.relationTable).id;

                if (tableId !== 0) {
                    values.relationTable = JSON.parse(values.relationTable).name;
                    let arr = [];
                    for (const ele of values.keys) {
                        arr.push({
                            relationValue: values[`relationValue-${ele}`],
                            alias: values[`alias-${ele}`]
                        })
                        delete values[`relationValue-${ele}`];
                        delete values[`alias-${ele}`];
                    }

                    delete values.keys;

                    values.relationArr = arr;
                } else {
                    values = 'no'
                }


                updateColumns({
                    id: relationData.id,
                    relationJson: values === 'no' ? values : JSON.stringify(values)
                }).then(res => {
                    message.success('修改成功！');
                    this.cancel();
                });

            }
        });
    };

    cancel = () => {
        const {form, handleCancel} = this.props;

        form.resetFields();
        this.setState({tableColumns: []});
        uuid = 0;

        handleCancel();

    }


    handleSelectChange = (value) => {
        let obj = JSON.parse(value);

        if (obj.id === 0) {
            this.setState({...this.state, tableColumns: []})
            return;
        }

        this.props.form.setFieldsValue({
            relationColumn: null,
        });

        fetchTableAndColumnsApi(obj.id).then(res => {
            this.setState({...this.state, tableColumns: res.data.data.columns})
        })


    }

    render() {

        const {visible, form: {getFieldDecorator, getFieldValue}} = this.props;

        const {tableOptions, tableColumns} = this.state;


        getFieldDecorator('keys', {initialValue: []});
        const keys = getFieldValue('keys');
        const formItems = keys.map((k, index) => {
            return (
                <Row gutter={40}>
                    <Col span={12}>
                        <FormItem
                            labelCol={{span: 5}}
                            wrapperCol={{span: 15}}
                            label='关联值'
                            key={k}
                        >
                            {getFieldDecorator(`relationValue-${k}`, {
                                rules: [{
                                    required: true,
                                    whitespace: true,
                                    message: "请选择关联的值",
                                }],
                            })(
                                <Select
                                    placeholder="请选择关联的值"
                                >
                                    {tableColumns.map((value, index) => {
                                        return (<Option value={value.name}>{value.name}</Option>)
                                    })}
                                </Select>
                            )}
                        </FormItem>
                    </Col>
                    <Col span={12}>
                        <FormItem
                            labelCol={{span: 6}}
                            wrapperCol={{span: 15}}
                            label='别名'
                            key={k}
                        >
                            {getFieldDecorator(`alias-${k}`, {
                                validateTrigger: ['onChange', 'onBlur'],
                                rules: [{
                                    required: true,
                                    whitespace: true,
                                    message: "请输入英文别名",
                                }],
                            })(
                                <Input placeholder="请输入英文别名" style={{width: '80%', marginRight: 8}}/>
                            )}
                            {keys.length > 1 ? (
                                <Icon
                                    className="dynamic-delete-button"
                                    type="minus-circle-o"
                                    disabled={keys.length === 1}
                                    onClick={() => this.remove(k)}
                                />
                            ) : null}
                        </FormItem>
                    </Col>
                </Row>
            );
        });


        return (
            <Modal
                title="表关联查询"
                visible={visible}
                onOk={this.handleOk}
                onCancel={this.cancel}
                width={700}
            >
                <Form onSubmit={this.handleSubmit}>
                    <Row gutter={40}>
                        <Col span={12}>
                            <FormItem
                                label="关联表"
                                labelCol={{span: 5}}
                                wrapperCol={{span: 15}}
                            >
                                {getFieldDecorator('relationTable', {
                                    rules: [{required: true, message: '请选择关联表'}],
                                })(
                                    <Select
                                        placeholder="请选择关联表"
                                        onChange={this.handleSelectChange}
                                    >
                                        {tableOptions.map((value, index) => {
                                            return (<Option
                                                value={JSON.stringify(value)}>{value.name}-{value.comment}</Option>)
                                        })}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        {tableColumns.length > 0 &&
                        <Col span={12}>
                            <FormItem
                                label="关联字段"
                                labelCol={{span: 6}}
                                wrapperCol={{span: 15}}
                            >
                                {getFieldDecorator('relationColumn', {
                                    rules: [{required: true, message: '请选择关联字段'}],
                                })(
                                    <Select
                                        placeholder="请选择关联字段"
                                    >
                                        {tableColumns.map((value, index) => {
                                            return (<Option value={value.name}>{value.name}</Option>)
                                        })}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        }
                    </Row>
                    {formItems}
                    <FormItem style={{textAlign: "center"}}>
                        <Button type="dashed" onClick={this.add} style={{width: '80%'}}>
                            <Icon type="plus"/> Add field
                        </Button>
                    </FormItem>
                </Form>

            </Modal>
        );
    }
}

const _RelationVerify = withRouter(Form.create()(RelationVerify));
export default _RelationVerify
